package com.itheima.demo02;

import java.io.*;
import java.net.Socket;
import java.util.UUID;

/**
 * @author Zhang_Han
 * @version 1.0
 * @date 2020/7/16 19:04
 */
public class MyRunnable implements Runnable {
    private Socket acceptRunnable;

    public MyRunnable(Socket accep) {
        this.acceptRunnable = accep;
    }

    @Override
    public void run() {
        BufferedOutputStream bos = null;
        //创建网络输入流读取客户端上传的文件;
        try {
            BufferedInputStream bis = new BufferedInputStream(acceptRunnable.getInputStream());
            //创建输出流,把读到的文件写到本地,一次读取一个字节数组;
            bos = new BufferedOutputStream(new FileOutputStream("demo_TCP\\Server\\" + UUID.randomUUID().toString() + ".jpg"));
            byte[] bytes = new byte[1024 * 8];
            int len;
            while ((len = bis.read(bytes)) != -1) {
                bos.write(bytes, 0, len);
                bos.flush();
            }

            //给客户端反馈上传成功;
            BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(acceptRunnable.getOutputStream()));
            bw.write("上传成功,感谢使用!");
            bw.newLine();
            bw.flush();

        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (bos != null) {
                try {
                    bos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                if (acceptRunnable != null) {
                    try {
                        acceptRunnable.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    }
}
